<?php
class VideoInfrastructureClient extends WebServiceClient {

	private $host;
	private $port;
	private $user;
	private $passpharse;
	private $public_key_file;
	private $private_key_file;
	
	public function __construct() {
		$config = ConfigReaderFactory::getInstance()->getConfigReader(VideoInfrastructureClientConfig::CLIENT_CONFIG_FILE)->getConfig();
		$ssh = $config->ssh;
		$this->host = (string) $ssh->host;
		$this->port = intval($ssh->port);
		$this->user = (string) $ssh->user;
		$this->passpharse = (string) $ssh->passpharse;
		$this->public_key_file = (string) $ssh->public_key;
		$this->private_key_file = (string) $ssh->private_key;
		
		$config = ConfigReaderFactory::getInstance()->getConfigReader(VideoInfrastructureClientConfig::WEB_SERVICE_CONFIG_FILE)->getConfig();
		$url = $config->webservice->url;
		$key = $config->webservice->key;
		parent::__construct($url, $key);
	}

	protected function createSource($login_id) {
		$parameters = func_get_args();
		return $this->invoke('VideoInfrastructure::CreateSource', $parameters);
	}

	protected function upload($login_id, $source_id, array $source_files) {
		$total_segment = count($source_files);
		$temp_segment_files = $this->invoke('VideoInfrastructure::GetUploadStorage', array($source_id, $total_segment));
		$temp_segment_files = json_decode(json_encode($temp_segment_files), TRUE);
		
		$ssh = new SSHAgent($this->host, $this->port, $this->user, $this->public_key_file, $this->private_key_file, $this->passpharse);

		$segment_files = array();
		foreach ($source_files as $segment_no => $source_file) {
			$destination_file = $temp_segment_files[$segment_no];
			$ret = $ssh->sendFile($source_file, $destination_file);
			$segment_files[$segment_no]['name'] = basename($source_file);
			$segment_files[$segment_no]['file'] = $destination_file;
		}

		return $this->invoke('VideoInfrastructure::Upload', array($login_id, $source_id, $segment_files));
	}

	public function uploadVideo($login_id, array $source_files) {
		$source_id = $this->createSource($login_id);
		if ($source_id <= 0) {
			error_log("ERROR CLASS:" . __CLASS__ . ", FUNCTION: " . __FUNCTION__ . ", LINE: " . __LINE__);
			error_log("ERROR - Create source record FAILS");
			error_log("Parameters: login_id = {$login_id}, source_files = " . var_export($source_files, TRUE));
			
			return -1; // create source record fails
		}
		
		return $this->upload($login_id, $source_id, $source_files);
	}
	
	public function __call($name, $arguments) {
		return $this->invoke("VideoInfrastructure::{$name}", $arguments);
	}
}
?>
